package com.boe.hbd.server.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

	private static final String PIC_ROOT = "pic.root";

	private FileUtil() {
	}

	public static String createFilePath(int seq) throws Exception {

		String pathStr = MD5Util.md5(String.valueOf(seq));
		String path = PropertiesUtil.getProperty(PIC_ROOT) + "/"
				+ pathStr.substring(0, 3) + "/" + pathStr.substring(3) + "/";
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
			
		}
		return path;
	}

	public static File createLargeFile(String path, int seq) throws Exception {
		File file = new File(path + String.valueOf(seq) + "l.jpg");
		if (!file.exists()) {
			file.createNewFile();
			return file;

		}
		throw new Exception();
	}

	public static File createSmallFile(String path, int seq) throws Exception {
		File file = new File(path + String.valueOf(seq) + "s.jpg");
		if (!file.exists()) {
			file.createNewFile();
			return file;

		}
		throw new Exception();
	}

	public static void save(int sequence, InputStream is) throws Exception {
		String path = createFilePath(sequence);
		File largeFile = createLargeFile(path, sequence);
		File smallFile = createSmallFile(path, sequence);
		OutputStream los = new FileOutputStream(largeFile);
		OutputStream sos = new FileOutputStream(smallFile);
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = is.read(buffer))) {
			los.write(buffer, 0, n);
		}
		is.close();
		los.close();

		InputStream largeImage = new FileInputStream(largeFile);
		ImageUtil.image(largeImage, sos);

	}
}
